package server;

import server.mapper.ContextMapper;
import server.mapper.HostMapper;
import server.mapper.Mapper;
import server.mapper.WrapperMapper;

import java.io.InputStream;
import java.net.Socket;
import java.net.URL;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;
    private Map<String,HttpServlet> servletMap;
    private Mapper mapper;

    public RequestProcessor(Socket socket, Map<String, HttpServlet> servletMap,Mapper mapper) {
        this.socket = socket;
        this.servletMap = servletMap;
        this.mapper = mapper;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            // 动态资源servlet请求
            HostMapper hostMapper = mapper.get(request.getHost());
            ContextMapper contextMapper = hostMapper.get(request.getAppName());
            WrapperMapper wrapperMapper = contextMapper.get(request.getUrl());

            HttpServlet httpServlet = wrapperMapper.getHttpServlet();
            // 静态资源处理
            if (httpServlet == null){
                response.outputHtml(request.getUrl());
            } else {
                httpServlet.service(request,response);
            }
            socket.close();

        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}